class Solution:
    def numIslands(self, grid):

        m = len(grid)
        if m == 0:
            return 0 
            
        n = len(grid[0])
        cnt = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] == "1":
                    cnt+=1
                    self.checkpoint(grid, i, j, m, n)

        
        return cnt
    
    def checkpoint(self, grid, a, b, m, n):

        if a<0 or a>=m:
            return
        if b<0 or b>=n:
            return

        if grid[a][b] == "1":
            grid[a][b] = "-1"

            self.checkpoint(grid, a-1, b, m, n)
            self.checkpoint(grid, a+1, b, m, n)
            self.checkpoint(grid, a, b-1, m, n)
            self.checkpoint(grid, a, b+1, m, n)